﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class UserControl_ControlExportToBrand : System.Web.UI.UserControl
{
    ClassExecute.ClassExecute dt;
    string str = webapp4U.Configuration.CurrentConnectionString;
    string error = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {


            BindChiNhanh(Session["sitecode"].ToString());
            BindLocation();
            BindGridSearch(Session["sitecode"].ToString());
        }
    }
    protected void imgBtnAdd_Click(object sender, ImageClickEventArgs e)
    {
        txtSoChungTuXuatHang.Text = "New";
        txtMaHang.Text = "";
        txtTenHang.Text = "";
        ViewState["flag"] = true;
        if (ViewState["KhoHangTemp"] != null)
        {
            ViewState["KhoHangTemp"] = null;

        }
        grvProduct.DataSource = null;
        grvProduct.DataBind();
    }
    protected void imgBtnSave_Click(object sender, ImageClickEventArgs e)
    {
         dt = new ClassExecute.ClassExecute();
         string DocNo = "";
        try
        {
            if ((bool)ViewState["flag"])
            {
                //insert
                DocNo = dt.GetDataDepend(str, "ls_getNextAdjTrnNo", CommandType.StoredProcedure, ref error);
                ViewState["flag"] = false;
            }
            else
            {
                //update
                bool kq = dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "ls_delTranTrn", ref error,
                   new SqlParameter("@DocNo", txtSoChungTuXuatHang.Text));
                DocNo = txtSoChungTuXuatHang.Text;
            }
            foreach (GridViewRow grv in grvProduct.Rows)
            {
                Label lblMaHang = (Label)grv.FindControl("lblMaHang");

               
                Label lblSL = (Label)grv.FindControl("lblSL");

                bool kq = dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "ls_addNewTranTrn", ref error,
                    new SqlParameter("@ItemKey", lblMaHang.Text),
                    new SqlParameter("@Location",ddlLocation.SelectedValue.ToString()),
                    new SqlParameter("@DocNo", DocNo),
                    new SqlParameter("@DocDate", txtDate.Text),
                    new SqlParameter("@stockQty", int.Parse(lblSL.Text)),
                    new SqlParameter("@ToBranch",ddlChiNhanh.SelectedValue.ToString()));
            }
           
            
            grvProduct.DataSource = null;
            grvProduct.DataBind();

            txtSoChungTuXuatHang.Text = "";
            txtMaHang.Text = "";
            txtTenHang.Text = "";

            if (ViewState["KhoHangTemp"] != null)
            {
                ViewState["KhoHangTemp"] = null;

            }
            uscMsgBox1.AddMessage("Lưu thông tin thành công", uscMsgBox.enmMessageType.Success);
        }
        catch (Exception ex)
        {
            uscMsgBox1.AddMessage("Hệ thống đang bảo trì", uscMsgBox.enmMessageType.Success);
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }   
    }
    protected void imgBtnDelete_Click(object sender, ImageClickEventArgs e)
    {
          dt = new ClassExecute.ClassExecute();
        
         try
         {
             bool kq = dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "ls_delTranTrn", ref error,
                  new SqlParameter("@DocNo", txtSoChungTuXuatHang.Text));
             if (kq)
             {
                 uscMsgBox1.AddMessage("Nghiệp vụ xóa thành công", uscMsgBox.enmMessageType.Success);

                 if (ViewState["KhoHangTemp"] != null)
                 {
                     ViewState["KhoHangTemp"] = null;

                 }

                 grvProduct.DataSource = null;
                 grvProduct.DataBind();

                 txtSoChungTuXuatHang.Text = "";
                 txtMaHang.Text = "";
                 txtTenHang.Text = "";
             }
             else
             {
                 uscMsgBox1.AddMessage("Hệ thống đang bảo trì", uscMsgBox.enmMessageType.Success);
             }

         }
         catch (Exception ex)
         {
             
             string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
             dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
         }   
    }
    protected void imgBtnFind_Click(object sender, ImageClickEventArgs e)
    {
        TabContainer1.ActiveTabIndex = 1;
    }
    void BindChiNhanh(string sitecode)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getTTPPUntil", CommandType.StoredProcedure,
                new SqlParameter("@sitecode",sitecode));
            dt.BindDropDownList(db, ddlChiNhanh, "sitecode", "sitename");
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }   

    }
    protected void txtMaHang_TextChanged(object sender, EventArgs e)
    {
        try
        {
            string Chuoi = txtMaHang.Text;
            int index = Chuoi.IndexOf("|");
            txtMaHang.Text = Chuoi.Substring(0, index - 1);
            txtTenHang.Text = Chuoi.Substring(index + 2, Chuoi.Length - index -2);
            txtSoLuong.Focus();

        }
        catch
        {
            return;
        }
    }
   
    void UpdateGridProduct()
    {
        DataTable table = new DataTable();
        if (ViewState["KhoHangTemp"] != null)
        {
            table = (DataTable)ViewState["KhoHangTemp"];
            foreach (DataRow dr in table.Rows)
            {
                if (dr[0].ToString() == txtMaHang.Text)
                {
                    dr[2] = Double.Parse(dr[2].ToString()) + Double.Parse(txtSoLuong.Text);
                    ViewState["KhoHangTemp"] = table;
                    grvProduct.DataSource = ViewState["KhoHangTemp"];
                    grvProduct.DataBind();
                    return;
                }
            }

            DataRow row = table.NewRow();
            //Fill All Columns with Data
            row[0] = txtMaHang.Text;
            row[1] = txtTenHang.Text;
            row[2] = Double.Parse(txtSoLuong.Text);

            table.Rows.Add(row);
        }
        else
        {


            DataColumn col1 = new DataColumn("Mã hàng");
            DataColumn col2 = new DataColumn("Tên hàng");
            DataColumn col3 = new DataColumn("Số lượng");

            col1.DataType = System.Type.GetType("System.String");
            col2.DataType = System.Type.GetType("System.String");
            col3.DataType = System.Type.GetType("System.Double");

            table.Columns.Add(col1);
            table.Columns.Add(col2);
            table.Columns.Add(col3);

            //Create a Row in the DataTable table
            DataRow row = table.NewRow();
            //Fill All Columns with Data
            row[col1] = txtMaHang.Text;
            row[col2] = txtTenHang.Text;
            row[col3] = Double.Parse(txtSoLuong.Text);

            table.Rows.Add(row);

            ViewState["KhoHangTemp"] = table;
        }
        grvProduct.DataSource = ViewState["KhoHangTemp"];
        grvProduct.DataBind();
    }
    protected void grvProduct_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            string keys = grvProduct.DataKeys[e.RowIndex].Value.ToString();
            TextBox txtSL = (TextBox)grvProduct.Rows[e.RowIndex].FindControl("txtSL");
            if ((txtSL.Text == "") || (txtSL.Text == "0"))
            {
                txtSL.Text = "1";
            }
            Double soluong = Double.Parse(txtSL.Text);
            DataTable table = new DataTable();
            table = (DataTable)ViewState["KhoHangTemp"];

            foreach (DataRow dr in table.Rows)
            {
                if (dr[0].ToString() == keys)
                {
                    dr[2] = soluong;
                    table.AcceptChanges();
                    ViewState["KhoHangTemp"] = table;

                    grvProduct.EditIndex = -1;
                    grvProduct.DataSource = ViewState["KhoHangTemp"];
                    grvProduct.DataBind();
                }
            }

        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }   
    }
    protected void grvProduct_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string keys = grvProduct.DataKeys[e.RowIndex].Value.ToString();

        DataTable table = new DataTable();
        table = (DataTable)ViewState["KhoHangTemp"];

        int i = 0;
        foreach (DataRow dr in table.Rows)
        {
            if (dr[0].ToString() == keys)
            {
                table.Rows[i].Delete();
                table.AcceptChanges();
                ViewState["KhoHangTemp"] = table;
                grvProduct.EditIndex = -1;
                grvProduct.DataSource = ViewState["KhoHangTemp"];
                grvProduct.DataBind();
                return;
            }
            i++;
        }
    }
    protected void grvProduct_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        grvProduct.EditIndex = -1;
        grvProduct.DataSource = ViewState["KhoHangTemp"];
        grvProduct.DataBind();
    }
    protected void grvProduct_RowEditing(object sender, GridViewEditEventArgs e)
    {
        grvProduct.EditIndex = e.NewEditIndex;
        grvProduct.DataSource = ViewState["KhoHangTemp"];
        grvProduct.DataBind();
    }
    protected void ddlChiNhanh_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindLocation();
    }
    void BindLocation()
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "K_GetLocation", CommandType.StoredProcedure,
                new SqlParameter("@SiteCode", ddlChiNhanh.SelectedValue.ToString()));
            dt.BindDropDownList(db, ddlLocation, "location", "description");
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }   
    }
    protected void grvSearch_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            if (e.CommandName == "chon")
            {

                GridViewRow grv = ((Control)e.CommandSource).NamingContainer as GridViewRow;
                Label lblSoChungTuXuatHang = (Label)grv.FindControl("lblSoChungTuXuatHang");

                DataTable db = dt.Get_Data_DataTable(str, ref error, "ls_getTranTrnDetail", CommandType.StoredProcedure,
                   new SqlParameter("@DocNo", lblSoChungTuXuatHang.Text));
                txtSoChungTuXuatHang.Text = db.Rows[0]["DocNo"].ToString();
                txtDate.Text = db.Rows[0]["DocDate"].ToString();
                try
                {
                    ddlChiNhanh.SelectedValue = db.Rows[0]["ToLocation"].ToString();
                   
                }
                catch
                {

                }
                try
                {
                    ddlLocation.SelectedValue = db.Rows[0]["Location"].ToString();
                }
                catch
                {
                }
                ViewState["KhoHangTemp"] = db;
        
                grvProduct.DataSource = ViewState["KhoHangTemp"];
                grvProduct.DataBind();


                ViewState["flag"] = false;
                TabContainer1.ActiveTabIndex = 0;
            }
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    void BindGridSearch(string sitecode)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "ls_getTranTrnNoList", CommandType.StoredProcedure,
                new SqlParameter("@siteCode", sitecode));
            grvSearch.DataSource = db;
            grvSearch.DataBind();
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void btAdd_Click(object sender, EventArgs e)
    {
        UpdateGridProduct();
    }
    protected void grvSearch_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grvSearch.PageIndex = e.NewPageIndex;
        BindGridSearch(Session["sitecode"].ToString());
    }
}